<template>
  <div class="page-content">
    <div class="header">
      <h3>流量监控</h3>
    </div>

    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="关键字">
          <el-input v-model="searchForm.keyword" placeholder="设备IP/用户昵称/服务器" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="时间范围">
          <div class="date-range-container">
            <el-date-picker
              v-model="startDate"
              type="datetime"
              placeholder="开始日期"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="new Date('2000-01-01 00:00:00')"
              style="width: 180px"
              :editable="false"
              :clearable="true"
              teleported
            />
            <span class="date-separator">至</span>
            <el-date-picker
              v-model="endDate"
              type="datetime"
              placeholder="结束日期"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="new Date('2000-01-01 23:59:59')"
              style="width: 180px"
              :editable="false"
              :clearable="true"
              teleported
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="danger" :disabled="selectedRows.length === 0" @click="handleBatchDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="traffic-table">
      <el-table
        v-loading="loading"
        :data="trafficList"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="70" />
        <el-table-column prop="user_nickname" label="用户名称" width="120">
          <template #default="scope">{{ scope.row.user_nickname || '-' }}</template>
        </el-table-column>
        <el-table-column prop="phone_id" label="设备ID" width="80" />
        <el-table-column prop="identification_numb" label="设备IP" min-width="140">
          <template #default="scope">{{ scope.row.identification_numb }}</template>
        </el-table-column>
        <el-table-column prop="consul_id" label="服务器" width="120">
          <template #default="scope">{{ scope.row.consul_id || '-' }}</template>
        </el-table-column>
        <el-table-column prop="total_traffic" label="总流量(KB)" width="120">
          <template #default="scope">{{ formatTraffic(scope.row.total_traffic) }}</template>
        </el-table-column>
        <el-table-column prop="average_traffic" label="平均流量(KB/s)" width="140">
          <template #default="scope">{{ formatTrafficRate(scope.row.average_traffic) }}</template>
        </el-table-column>
        <el-table-column prop="total_time" label="总时长(秒)" width="100">
          <template #default="scope">{{ formatTime(scope.row.total_time) }}</template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column prop="updated_at" label="更新时间" width="180" />

        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="showTrafficDetail(scope.row)" plain>详情</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)" plain>删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="流量详情" width="60%">
      <div>
        <el-descriptions border :column="2">
          <el-descriptions-item label="用户">{{ currentDetail.user_nickname || '-' }}</el-descriptions-item>
          <el-descriptions-item label="设备ID">{{ currentDetail.phone_id }}</el-descriptions-item>
          <el-descriptions-item label="设备IP">{{ currentDetail.identification_numb }}</el-descriptions-item>
          <el-descriptions-item label="服务器">{{ currentDetail.consul_id }}</el-descriptions-item>
          <el-descriptions-item label="总流量 (KB)">{{ formatTraffic(currentDetail.total_traffic) }}</el-descriptions-item>
          <el-descriptions-item label="平均流量 (KB/s)">{{ formatTrafficRate(currentDetail.average_traffic) }}</el-descriptions-item>
          <el-descriptions-item label="总时长 (秒)">{{ formatTime(currentDetail.total_time) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentDetail.created_at }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ currentDetail.updated_at }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getTrafficList, 
  deleteTrafficRecords, 
  type TrafficData
} from '@/Newapi/traffic'

// 格式化日期为字符串
const formatDateToString = (date: Date, withTime = true): string => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  
  if (withTime) {
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  
  return `${year}-${month}-${day}`
}

// 获取今天开始时间
const getTodayStart = (): string => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return formatDateToString(today)
}

// 获取今天结束时间
const getTodayEnd = (): string => {
  const today = new Date()
  today.setHours(23, 59, 59, 999)
  return formatDateToString(today)
}

// 搜索表单
const searchForm = reactive({
  keyword: '',
})

// 日期范围
const startDate = ref(getTodayStart())
const endDate = ref(getTodayEnd())

// 表格数据
const trafficList = ref<TrafficData[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedRows = ref<TrafficData[]>([])

// 详情相关
const detailVisible = ref(false)
const currentDetail = ref<TrafficData>({} as TrafficData)

// 加载流量列表
const loadTrafficList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchForm.keyword,
      start_time: startDate.value || undefined,
      end_time: endDate.value || undefined
    }
    
    const res = await getTrafficList(params)
    if (res.code === 200 && res.data) {
      const responseData = res.data
      trafficList.value = Array.isArray(responseData.list) ? responseData.list : []
      total.value = typeof responseData.total === 'number' ? responseData.total : 0
    } else {
      ElMessage.error(res.msg || '获取流量数据失败')
    }
  } catch (error) {
    console.error('获取流量列表出错:', error)
    ElMessage.error('获取流量数据失败')
  } finally {
    loading.value = false
  }
}

// 格式化流量显示
const formatTraffic = (bytes: number) => {
  if (bytes === 0) return '0 KB'
  
  // 输入值已经是KB，需要从KB开始转换
  const units = ['KB', 'MB', 'GB', 'TB', 'PB']
  const k = 1024
  let value = bytes
  let i = 0
  
  while (value >= k && i < units.length - 1) {
    value /= k
    i++
  }
  
  return parseFloat(value.toFixed(2)) + ' ' + units[i]
}

// 格式化流量速率
const formatTrafficRate = (bytesPerSecond: number) => {
  if (bytesPerSecond === 0) return '0 KB/s'
  
  // 输入值已经是KB/s，从KB/s开始转换
  const units = ['KB/s', 'MB/s', 'GB/s', 'TB/s']
  const k = 1024
  let value = bytesPerSecond
  let i = 0
  
  while (value >= k && i < units.length - 1) {
    value /= k
    i++
  }
  
  return parseFloat(value.toFixed(2)) + ' ' + units[i]
}

// 格式化时间
const formatTime = (seconds: number) => {
  if (seconds < 60) {
    return seconds + '秒'
  } else if (seconds < 3600) {
    const minutes = Math.floor(seconds / 60)
    return minutes + '分钟' + (seconds % 60 ? (seconds % 60) + '秒' : '')
  } else {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    return hours + '小时' + (minutes ? minutes + '分钟' : '')
  }
}

// 处理查询
const handleSearch = () => {
  currentPage.value = 1
  loadTrafficList()
}

// 重置查询
const resetSearch = () => {
  searchForm.keyword = ''
  startDate.value = getTodayStart()
  endDate.value = getTodayEnd()
  currentPage.value = 1
  loadTrafficList()
}

// 表格选择改变
const handleSelectionChange = (rows: TrafficData[]) => {
  selectedRows.value = rows
}

// 页码改变
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadTrafficList()
}

// 每页数量改变
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadTrafficList()
}

// 删除记录
const handleDelete = (row: TrafficData) => {
  ElMessageBox.confirm('确定要删除此流量记录吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteTrafficRecords([row.id])
      if (res.code === 200) {
        ElMessage.success('删除成功')
        loadTrafficList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除出错:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条记录吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id)
      const res = await deleteTrafficRecords(ids)
      if (res.code === 200) {
        ElMessage.success('批量删除成功')
        loadTrafficList()
      } else {
        ElMessage.error(res.msg || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除出错:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {})
}

// 显示流量详情
const showTrafficDetail = (row: TrafficData) => {
  currentDetail.value = row
  detailVisible.value = true
}

// 页面挂载时加载数据
onMounted(() => {
  loadTrafficList()
})
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;

  /* 禁用触摸事件 */
  :deep(.el-date-editor) {
    touch-action: none;
  }
  
  /* 解决日期选择器弹出层问题 */
  :deep(.el-picker-panel) {
    touch-action: pan-y;
  }
  
  :deep(.el-picker__popper) {
    touch-action: none;
  }

  .date-range-container {
    display: flex;
    align-items: center;
    
    .date-separator {
      margin: 0 5px;
    }
  }

  .header {
    padding-bottom: 15px;
    border-bottom: 1px solid var(--art-border-color);

    h3 {
      font-size: 18px;
      font-weight: 500;
    }
  }
  
  .search-bar {
    margin-top: 20px;
    margin-bottom: 20px;
  }
  
  .traffic-table {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 